// pages/tea-detail/tea-detail.js
import axios from '../../utils/axios';
import checkSub from '../../utils/checkSub';
import {
  bannerFormat
} from '../../utils/imgFormat'
import dayjs from 'dayjs';
const app = getApp();
const formatDate = 'YYYY-MM-DD';

function sortTime(item) {
  if (dayjs(item.startTime).isAfter(dayjs(item.endTime))) {
    const temp = item.startTime;
    item.startTime = item.endTime;
    item.endTime = temp;
  }
  return item;
}
Page({
  data: {
    /**
     * 轮播图配置
     */
    swiperConfig: {
      current: 0,
      autoplay: true,
      duration: '500',
      interval: 5000,
      jsLoading: false,
      navigation: {
        type: 'dots',
      },
      swiperImageProps: {
        mode: 'widthFix',
      },
    },
    showUserInfoModal:false,
    pageDate: dayjs().format(formatDate),
    duration: 0, //已选时长
    pickerStart: Date.now(),
    dateVisible: false,
    timeItems: [],
    item: {},
    imgSrcs: [],
    roomUsaged: [],
    mtqDuration: 0,
    mtqCode: "",
    confirmBtn: { content: '确定', variant: 'base' },
    actived: [],
    hasName: true, // 微信昵称
    hasPhone: true, // true 已获得手机号，false 未获得手机号
  },
  onLoad(options) {
    const member = wx.getStorageSync('memberInfo')
    const {
      phone,
      name
    } = JSON.parse(member || "{}")
    if (name === undefined || name === "") {
      this.setData({
        hasName: false
      })
    }else{
      this.setData({
        nickName:name
      })
    }
    if (phone === undefined || phone === "") {
      this.setData({
        hasPhone: false
      })
    }
    if (options?.mtqCode) {
      this.setData({
        mtqCode: options.mtqCode,
        mtqDuration: options.mtqDuration
      })
    }
    if (options?.item) {
      const item = JSON.parse(options.item);
      const imgSrcs = item.banners.map((item) => bannerFormat(item.url));
      this.setData({
        item,
        imgSrcs
      });
      this.setTimeItems();

      this.optionsItem = item;
      this.getRoomUsagedTimer = setInterval(() => {
        this.getRoomUsaged(item);
      }, 10000);
    } else {
      wx.switchTab({
        url: `/pages/home/home`
      });
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getRoomUsaged(this.optionsItem);
  },
  onUnload() {
    if (this.getRoomUsagedTimer) {
      clearInterval(this.getRoomUsagedTimer);
    }
  },
  getUserInfoModal(){
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        const nickName = res.userInfo.nickName
        axios.post("/app/createMember", {
          wxId: wx.getStorageSync('openid'),
          phone: this.data.phoneNumber,
          name : nickName,
        }).then(res => {
          wx.setStorageSync('memberInfo', JSON.stringify(res.data));
          this.setData({
            showUserInfoModal:false
          })
          this.pay();
        })
      },fail(err){
        console.log(err);
        resolve("");
      }
    })
    
  },
  async getPhoneNumber(e) {
    const code = e.detail.code;
    axios.get('/app/getPhoneNumber', {
      code
    }).then(res => {
      const phoneNumber = res.data.phone_info.phoneNumber;
      if (phoneNumber) {
        this.setData({
          showUserInfoModal:true,
          phoneNumber
        })
      }
    })
    


  },
  /**
   * 获取已使用的时间段
   * @param {option item} item
   */
  async getRoomUsaged(item) {
    if (!item) {
      return
    }
    const {
      data
    } = await axios.get('/app/getRoomUsaged', {
      roomId: item.ID
    });
    if (data.length > 0) {
      this.setData({
        roomUsaged: data
      });
      this.setData({
        used: []
      });
    }
    this.setTimeItems(this.data.pageDate)
  },

  /**
   * 获取可选择的时间段
   * @param {Date} date
   */
  setTimeItems(date = dayjs().format(formatDate)) {
    let times = [];
    for (let hour = 0; hour <= 23; hour++) {
      for (let minute = 0; minute <= 30; minute += 30) {
        let time = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
        let currentTime = dayjs(`${date} ${time}`);
        let type = currentTime.isBefore(dayjs()) ? "disabled" : "";
        this.data.roomUsaged.forEach(usage => {
          let startTime = dayjs(usage.start_time).subtract(1, "second");
          let endTime = dayjs(usage.end_time).add(1, "second");
          if (startTime.isBefore(currentTime) && currentTime.isBefore(endTime)) {
            type = "disabled";
          }
        });
        this.data.actived.forEach(usage => {
          let startTime = dayjs(usage.startTime).subtract(1, "second");
          let endTime = dayjs(usage.endTime).add(1, "second");
          if (startTime.isBefore(currentTime) && currentTime.isBefore(endTime)) {
            type = "active";
          }
        });
        times.push({
          type,
          time
        });
      }
    }
    let duration = 0;
    if (this.data.actived.length > 0) {
      duration = dayjs(this.data.actived[0].endTime).diff(dayjs(this.data.actived[0].startTime)) / 60000;
    }
    this.setData({
      timeItems: times,
      duration: duration / 60
    })
  },
  handleTimeBtn(e) {
    const {
      cur,
      type
    } = e.currentTarget.dataset;
    if (type === "disabled") {
      return
    }
    const {
      pageDate
    } = this.data;
    const activeDate = `${pageDate} ${cur.time}:00`
    // 一个没选时，并且点击可选时间
    if (type === "" && this.data.actived.length === 0) {
      this.setData({
        actived: [{
          startTime: activeDate,
          endTime: activeDate
        }].map(sortTime)
      })
      this.setTimeItems(pageDate)
      return
    }
    // 选了开始时间，并且点击可选时间
    if (type === "" && this.data.actived.length === 1) {
      // 这里需要加一个判断，如果开始时间和结束时间中间有已使用时间，则不操作
      if (true) {
        this.data.actived[0].endTime = activeDate
        this.setData({
          actived: this.data.actived.slice().map(sortTime)
        })
        this.setTimeItems(pageDate)
      }
      return
    }
    // 点击已选时间 并且只有一个时间块，取消
    if (type === "active" && this.data.actived[0].endTime === this.data.actived[0].startTime) {
      this.setData({
        actived: []
      })
      this.setTimeItems(pageDate)
      return
    }
    // 点击已选时间 并且不止一个时间块
    if (type === "active" && this.data.actived[0].endTime !== this.data.actived[0].startTime) {
      this.data.actived[0].startTime = activeDate
      this.setData({
        actived: this.data.actived.slice().map(sortTime)
      })
      this.setTimeItems(pageDate)
      return
    }


  },
  /**
   * 展示时间选择
   */
  showPicker() {
    this.setData({
      dateVisible: true
    });
  },

  /**
   * 隐藏时间选择
   */
  hidePicker() {
    this.setData({
      dateVisible: false
    });
  },

  /**
   * 切换当前的日期
   * @param {e}
   */
  onConfirm(e) {
    const {
      value
    } = e.detail;
    this.setData({
      pageDate: value
    })
    this.setTimeItems(value);
    this.hidePicker();
  },
  checkMtq() {
    const {
      duration,
      mtqDuration = 0
    } = this.data;
    if (duration * 60 <= mtqDuration || mtqDuration === 0) {
      return false
    }
    wx.showToast({
      title: '可用时长为 ' + mtqDuration + " 分钟",
      icon: "none"
    })
    return true
  },
  // 立即结算
  async pay() {
    const {
      actived,
      duration,
      mtqCode,
      jsLoading,
      item = {}
    } = this.data;
    if (jsLoading) {
      return;
    }
    if (this.checkMtq()) {
      return
    }
    let price = null;
    item.price_list.forEach((v, index) => {
      if (duration <= v.duration && !price) {
        price = v.price;
      }
      if (index + 1 === item.price_list.length && !price) {
        price = v.price;
      }
    });
    const params = {
      source: '小程序',
      startTime: actived[0].startTime,
      endTime: actived[0].endTime,
      price: price * duration,
      companyId: item.company_id,
      roomId: item.ID,
      status: 1,
      remark: '',
      type: 1,
      wxId: wx.getStorageSync('openid')
    };
    if (mtqCode) {
      params.source = "美团";
      params.price = 0;
      params.status = 2;
      const isContinue = await this.hexiaomt(mtqCode);
      if (!isContinue) {
        return;
      }
    }
    this.setData({
      jsLoading: true
    })
    const {
      orderId
    } = await axios.post('/app/createOrder', params);
    this.setData({
      jsLoading: false
    })
    if (params.source === "小程序") {
      const itemData = JSON.stringify({
        ...this.data.item,
        orderId
      });
      app.globalData.orderDetail[orderId] = {
        ...this.data.item,
        orderId
      };
      wx.navigateTo({
        url: `/pages/pay/pay?item=${itemData}`
      });
    } else {
      this.payCallback(orderId);
    }

  },
  payCallback(orderId) {
    wx.showToast({
      title: '支付成功',
      icon: 'none'
    })
    checkSub(['ZAen9G6QJvaBN_B8itISxyfmf2bL5vPHNyGC8WRPOKE']).finally(() => {
      wx.redirectTo({
        url: `/pages/result/pay/index?orderId=${orderId}`,
      });
    });
  },
  async hexiaomt(code) {
    // 核销团购券
    const result = await axios.post("/app/mtConsume", {
      receiptCode: code,
      companyId: this.data.item.company_id
    })
    const res = JSON.parse(result);
    if (res.code === 200) {
      return true;
    } else {
      wx.showToast({
        title: res.msg,
        icon: "error",
        duration: 2000
      })
      return false;
    }
  },
  previewImg(){
    const {imgSrcs} = this.data;
    if(imgSrcs&&imgSrcs.length>0){
      wx.previewImage({  
        current: imgSrcs[0], // 当前显示图片的http链接  
        urls: imgSrcs
      });  
    }
    
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});